package com.xquant.system.schedule;

import com.xquant.system.exception.ServiceException;
import com.xquant.system.service.impl.TwcBndPrimaryKeyTestServiceImpl;
import com.xquant.system.service.impl.VwcBndDefaultServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.Scheduled;


import static com.xquant.system.common.LockKeys.TWCBND_PRIMARY_KEY_TEST;
import static com.xquant.system.common.LockKeys.VWCBND_DEFAULT;
import static com.xquant.system.common.ResultCode.LOCK_FAILED;


/**
 * 定时任务
 *
 */
@Configuration
@Slf4j
public class TimedTasks {

    /**
     * 秒 分 时 日 月 周 年
     * *：每秒都执行
     * 1-3 ：1到3秒执行
     * 0/3 ：每3秒执行一次
     * 1,3,5 ：1,3,5秒执行
     * ?: 不指定
     * 日和周不能同时指定，指定其中之一，则另一个设置为?
     */
    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private VwcBndDefaultServiceImpl vwcBndDefaultService;
    @Autowired
    private TwcBndPrimaryKeyTestServiceImpl twcBndPrimaryKeyTestService;


//    @Scheduled(cron = "0 0/1 * * * ?")
    public void InternalCodeFusionTask() {
        // 获取锁
        RLock lock = redissonClient.getLock(TWCBND_PRIMARY_KEY_TEST);
        // 锁住
        boolean locked = lock.tryLock();
        if (!locked) {
            log.warn("ScheduleLock {}: getting lock failed",TWCBND_PRIMARY_KEY_TEST);
            throw new ServiceException(LOCK_FAILED,"获取锁失败");
        }
        try {
            twcBndPrimaryKeyTestService.internalCodeFusion();
        } catch (Exception e) {
            log.error("ScheduleLock {}: lock interrupted",TWCBND_PRIMARY_KEY_TEST,e);
            e.printStackTrace();
        } finally {
            log.info("解锁");
            lock.unlock();
        }
    }

//    @Scheduled(cron = "0 0/1 * * * ?")
    public void ThreeWayComparisonTask() {
        // 获取锁
        RLock lock = redissonClient.getLock(VWCBND_DEFAULT);
        // 锁住
        boolean locked = lock.tryLock();
        if (!locked) {
            log.warn("ScheduleLock {}: getting lock failed", VWCBND_DEFAULT);
            throw new ServiceException(LOCK_FAILED,"获取锁失败");
        }
        try {
            vwcBndDefaultService.threeWayComparison();
        } catch (Exception e) {
            log.error("ScheduleLock {}: lock interrupted", VWCBND_DEFAULT, e);
            e.printStackTrace();
        } finally {
            log.info("解锁");
            lock.unlock();
        }
    }

}
